import os
import hashlib
from flask import Flask, current_app
from flask_avatars import Avatars
from flask_avatars.identicon import Identicon

avatars = Avatars()

def init_app(app: Flask):
    avatars.init_app(app)
    if app.config['AVATARS_SAVE_PATH'] is None:
        app.config['AVATARS_SAVE_PATH'] = app.instance_path

def generate_avatar(email: str):
    avatar = Identicon()
    avatar_hash = hashlib.md5(str(email).lower().encode('utf-8')).hexdigest()
    data = avatar.get_image(avatar_hash, 150, 150, 15)

    filename = 'avatars/%s.png' % avatar_hash
    path = current_app.config['AVATARS_SAVE_PATH']

    try:
        os.makedirs(os.path.join(path, 'avatars'))
    except OSError:
        pass

    avatar.save(data, save_location=os.path.join(path, filename))
    return '%s.png' % avatar_hash
